<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/6/1
 * Time: 11:32
 */

namespace app\common\lib;


use app\exception\IndexException;
use App\exceptions\CommonException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtToken
{
    protected $key;

    protected static $instance;

    public function __construct()
    {
        $this->key = config('param.jwt_secret');
    }

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }


        return new self();
    }

    /**
     * 生成token
     * @param $userInfo
     * @param $expireTime
     * @return string
     */
    public function createToken($userInfo, $expireTime=0)
    {
        $expireTime==false && $expireTime = (30*12*30*86400);
        $time = time();
        $payload = array(
            //  签发者
            "iss" => "",
            //  面向用户，可以为空
            "aud" => "",
            // 签发的时间
            "iat" => $time,
            // 在什么时候JWT生效？
            "nbf" => $time,
            //  token 过期时间
            "exp" => $time+$expireTime,
        );

        $payload = array_merge($payload,$userInfo);
        $token = JWT::encode($payload,$this->key,'HS256');

        return $token;
    }

    /**
     * 解密token
     * @param $token
     * @return mixed
     * @throws \Exception
     */
    public function validateToken($token)
    {
        try {
            $decoded = JWT::decode($token, new Key($this->key, 'HS256'));
            return json_decode(json_encode($decoded), true);
        }catch (\UnexpectedValueException $e){
            throw new IndexException(1000,'token:'.$e->getMessage());
        }catch (IndexException $e){
            throw new IndexException(1000,'token:'.$e->getMessage());
        }catch (\Throwable $e){
            throw new IndexException(1000,'token:'.$e->getMessage());
        }
    }
}